﻿'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('=== testLikeFlow 开始 ===');
  console.log('接收参数:', event);
  
  try {
    const { userId, postId, receiverId, postTitle } = event;
    
    if (!userId || !postId || !receiverId) {
      return {
        code: 400,
        msg: '参数缺失',
        data: { userId, postId, receiverId }
      };
    }
    
    // 检查是否是自己给自己的帖子点赞
    if (userId === receiverId) {
      console.log('检测到自点赞，跳过消息生成');
      return {
        code: 200,
        msg: '自点赞，无需生成消息',
        data: {
          userId: userId,
          skipMessage: true,
          reason: '自点赞'
        }
      };
    }
    
    console.log('1. 开始测试点赞流程');
    
    // 1. 查询用户信息
    console.log('2. 查询用户信息，userId:', userId);
    const userRes = await db.collection('uni-id-users')
      .doc(userId)
      .field({ nickname: true, avatar_file: true })
      .get();
    
    if (!userRes.data || userRes.data.length === 0) {
      return {
        code: 404,
        msg: '用户不存在',
        data: { userId, queryResult: userRes }
      };
    }
    
    const userData = userRes.data[0];
    const nickname = userData.nickname || '用户';
    const avatar = userData.avatar_file?.url || '/static/images/default-avatar.png';
    
    console.log('3. 用户信息:', { nickname, avatar });
    
    // 2. 创建互动消息
    console.log('4. 创建互动消息');
    const messageData = {
      receiver_id: receiverId,
      sender_id: userId,
      sender_nickname: nickname,
      sender_avatar: avatar,
      post_id: postId,
      post_title: postTitle || '测试帖子',
      type: 'like',
      content: `${nickname} 点赞了您的帖子《${postTitle || '测试帖子'}》`,
      is_read: false,
      create_time: Date.now()
    };
    
    console.log('5. 准备插入数据:', messageData);
    
    const result = await db.collection('interaction-messages').add(messageData);
    
    console.log('6. 插入结果:', result);
    
    return {
      code: 200,
      msg: '测试成功',
      data: {
        userId: userId,
        nickname: nickname,
        avatar: avatar,
        messageId: result.id,
        messageData: messageData
      }
    };
    
  } catch (error) {
    console.error(' testLikeFlow 异常:', error);
    return {
      code: 500,
      msg: '测试失败: ' + error.message,
      error: error
    };
  }
};
